export class Sprite {
    public canvas!: HTMLCanvasElement;
    private width!: number;
    private height!: number;
    private texture!: HTMLImageElement;
    private angle!: number;
    private pos!: number[];
    private anchor!: number[];

    constructor(attribute: {
        texture: HTMLImageElement;
        width: number;
        height: number;
        angle?: number; // 角度
        pos?: number[]; // 定位
        anchor?: number[]; // 锚点
    }) {
        const {
            width, height,
            texture, angle = 0,
            pos, anchor,
        } = attribute;
        this.width = width;
        this.height = height;
        this.texture = texture;
        this.angle = angle;
        this.pos = pos || [0, 0];
        this.anchor = anchor || [0, 0];
    }

    public render(sceneSize: number[]) {
        // // 创建画板
        const canvas = document.createElement('canvas');
        canvas.width = sceneSize[0];
        canvas.height = sceneSize[1];
        const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
        // 计算某些需要的值
        const drawPos = [this.width * this.anchor[0], this.height * this.anchor[1]];
        // 绘制元素
        ctx.save(); // 保存状态
        ctx.translate(this.pos[0], this.pos[1]);
        ctx.rotate(this.angle * Math.PI / 180);
        if (!this.texture) {
            return canvas;
        }
        ctx.drawImage(
            this.texture,
            -drawPos[0],
            -drawPos[1],
            this.width, this.height
        );
        ctx.restore(); // 恢复状态
        this.canvas = canvas;
        return canvas;
    }
}
